/*
 * @lc app=leetcode.cn id=40 lang=java
 *
 * [40] 组合总和 II
 */

// @lc code=start
import java.util.*;
class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        boolean[] used = new boolean[candidates.length];
        Arrays.fill(used, false);
        Arrays.sort(candidates);
        backtracking(candidates, target, 0, 0, used);
        return res;
    }

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new LinkedList<>();
    private void backtracking(int[] candidates, int target, int sum, int startIndex, boolean[] used) {
        if(sum > target) {
            return;
        }
        if(sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        for(int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
            if(i > 0 && candidates[i] == candidates[i-1] && used[i-1] == false) {
                continue;
            }

            sum += candidates[i];
            path.add(candidates[i]);
            used[i] = true;
            backtracking(candidates, target, sum, i+1, used);
            used[i] = false;
            path.removeLast();
            sum -= candidates[i];
        }
    }
}
// @lc code=end

